/**
 * 用户相关API接口
 */
import { get, post, put } from '@/utils/request.js'

/**
 * 用户登录
 * @param {Object} data - 登录数据
 * @param {string} data.username - 用户名
 * @param {string} data.password - 密码
 */
export const login = (data) => {
  return post('/auth/login', data)
}

/**
 * 用户注册
 * @param {Object} data - 注册数据
 * @param {string} data.username - 用户名
 * @param {string} data.email - 邮箱
 * @param {string} data.password - 密码
 */
export const register = (data) => {
  return post('/auth/register', data)
}

/**
 * 获取用户信息
 */
export const getUserInfo = () => {
  return get('/user/info')
}

/**
 * 更新用户信息
 * @param {Object} data - 用户信息
 */
export const updateUserInfo = (data) => {
  return put('/user/info', data)
}

/**
 * 修改密码
 * @param {Object} data - 密码数据
 * @param {string} data.oldPassword - 原密码
 * @param {string} data.newPassword - 新密码
 */
export const changePassword = (data) => {
  return put('/user/password', data)
}

/**
 * 上传头像
 * @param {string} filePath - 文件路径
 */
export const uploadAvatar = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + '/user/avatar',
      filePath,
      name: 'avatar',
      header: {
        Authorization: `Bearer ${uni.getStorageSync('token')}`
      },
      success: (uploadRes) => {
        const data = JSON.parse(uploadRes.data)
        if (data.code === 200) {
          resolve(data.data)
        } else {
          reject(new Error(data.message))
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

/**
 * 获取学习统计
 */
export const getLearningStatistics = () => {
  return get('/statistics/learning')
}

/**
 * 获取成就徽章
 */
export const getAchievements = () => {
  return get('/statistics/achievements')
}

/**
 * 获取学习日历
 */
export const getLearningCalendar = () => {
  return get('/statistics/calendar')
}

/**
 * 获取学习记录
 */
export const getLearningHistory = () => {
  return get('/learning/history')
}

export default {
  login,
  register,
  getUserInfo,
  updateUserInfo,
  changePassword,
  uploadAvatar,
  getLearningStatistics,
  getAchievements,
  getLearningCalendar,
  getLearningHistory
}